﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ControlTest
{
	public class CustomListView : ListView
	{
		public class DrawSubItemInstruction
		{
			public Rectangle DisplayRectangle { get; set; }
			public TextImageRelation TextImageRelation { get; set; }
			public ContentAlignment TextAlignment { get; set; }
			public ContentAlignment ImageAlignment { get; set; }

			public static DrawSubItemInstruction Default
			{
				get
				{
					return new DrawSubItemInstruction { DisplayRectangle = Rectangle.Empty, ImageAlignment = ContentAlignment.MiddleLeft, TextAlignment = ContentAlignment.MiddleLeft, TextImageRelation = TextImageRelation.ImageBeforeText };
				}
			}
		}

		public IList<DrawSubItemInstruction> DrawingInstructions { get; private set; }

		public CustomListView()
		{
			OwnerDraw = true;
			DoubleBuffered = true;
			DrawingInstructions = new List<DrawSubItemInstruction>();
		}

		protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e)
		{
			base.OnDrawColumnHeader(e);
			e.DrawDefault = true;
		}

		protected override void OnDrawItem(DrawListViewItemEventArgs e)
		{
			base.OnDrawItem(e);
			e.DrawBackground();
			DrawPart(e.Graphics, e.Bounds, e.Item, e.State, 0);
		}

		protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e)
		{
			base.OnDrawSubItem(e);
			if (e.ColumnIndex > 0)
			{
				e.DrawBackground();
				DrawPart(e.Graphics, e.Bounds, e.Item, e.ItemState, e.ColumnIndex);
			}
		}

		private void DrawPart(Graphics graphics, Rectangle bounds, ListViewItem listViewItem, ListViewItemStates listViewItemStates, int col)
		{
			var i = listViewItem.SubItems[col];
			var inst = DrawingInstructions.Count == this.Items.Count ? DrawingInstructions[listViewItem.Index] : DrawSubItemInstruction.Default;
			graphics.DrawImageAndText(bounds, i.Text, i.Font, listViewItem.ImageList.Images[i.ImageIndex],
				inst.TextAlignment, inst.ImageAlignment, inst.TextImageRelation, listViewItem.ForeColor, true, 0);
		}
	}
}
